import requests
import re
from PIL import Image

try:
    import cookielib
except:
    import  http.cookiejar as cookielib

agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"

headers = {

    "HOST":"www.zhihu.com",
    "Referer": "https://www.zhihu.com",
    "User-Agent": agent

}

session = requests.session()
# 保村cookies到文件
session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")

try:
    session.cookies.load(ignore_discard=True)
except:
    print("cookies is not exist")

# import scrapy
# Captcha-englishImg
# captcha

from bs4 import BeautifulSoup


def get_captcha():
    import time
    t = str(int(time.time() * 1000))
    captcha_url = 'https://www.zhihu.com/captcha.gif?r={0}&type=login'.format(t)
    t = session.get(captcha_url, headers=headers)
    with open("captcha.jpg", "wb") as f:
        f.write(t.content)
    try:
        img = Image.open('captcha.jpg')
        img.show()

    except Exception as e:
        print(e)
    captcha = input("输入验证码：")
    img.close()
    return captcha


def zhihu_login(account, password):

    post_url =None
    post_data = None
    captcha = get_captcha()
    if re.match("^1\d{10}",account):
        print("手机号码登陆")
        post_url = "https://www.zhihu.com/signin"
        post_data = {
            "_xsrf": "STJThI54odhj8YxNZmKVnWR71Dc5T0qJ",
            "username": account,
            "password": password,
            "captcha": captcha
        }

    else:
        if '@' and '.'in account:
            print("邮箱登陆")
            post_url = "https://www.zhihu.com/signin"
            post_data = {
                "_xsrf": "STJThI54odhj8YxNZmKVnWR71Dc5T0qJ",
                "email": account,
                "password": password,
                "captcha": captcha
            }

    # resp = requests.post(url=post_url,data=post_data, headers=headers)
    # 高效方法
    resp_session = session.post(url=post_url,data=post_data, headers=headers)
    session.cookies.save()


zhihu_login('15213379869','belief417@zhihu.com')

# https://www.zhihu.com/

def check_login():
    # 通过访问个人中心页面返回的状态码，验证是否登陆成功
    inbox_url = "https://www.zhihu.com/inbox"
    response = session.get(inbox_url, headers=headers)

    if response.status_code ==200:
        print("成功")
        # print(requests.get(inbox_url, headers=headers).text)
        # print(response.text)
        with open('index.html', "w", encoding="utf-8") as rf:
            rf.write(response.text)
        return True

    else:
        print("失败")
        return False
    pass


check_login()